import os
import argparse
import logging
import shutil
import sys
import shutil


def configure_logging(level):

    # add 'levelname_c' attribute to log resords
    orig_record_factory = logging.getLogRecordFactory()
    log_colors = {
        logging.DEBUG:     "\033[1;34m",  # blue
        logging.INFO:      "\033[1;32m",  # green
        logging.WARNING:   "\033[1;35m",  # magenta
        logging.ERROR:     "\033[1;31m",  # red
        logging.CRITICAL:  "\033[1;41m",  # red reverted
    }

    def record_factory(*args, **kwargs):
        record = orig_record_factory(*args, **kwargs)
        record.levelname_c = "{}{}{}".format(
            log_colors[record.levelno], record.levelname, "\033[0m")
        return record

    logging.setLogRecordFactory(record_factory)

    # now each log record object would contain 'levelname_c' attribute
    # and you can use this attribute when configuring logging using your favorite
    # method.
    # for demo purposes I configure stderr log right here

    formatter_c = logging.Formatter(
        "[%(asctime)s] %(levelname_c)s %(message)s")

    stderr_handler = logging.StreamHandler()
    stderr_handler.setLevel(level)
    stderr_handler.setFormatter(formatter_c)

    root_logger = logging.getLogger('')
    root_logger.setLevel(logging.DEBUG)
    root_logger.addHandler(stderr_handler)

#	rsync -avm  --include='src/third_party/**.h' -f 'hide,! */' src newsrc2
#


def collect_header(path):
    logging.info("collecting header")

    if not os.path.isdir(path):
        logging.error(f"header path[{path}] not exist")
        return
    path_list = [
        ("api",), ("audio",), ("base",), ("call",),
        ("common_video",), ("logging",), ("media",), ("common_audio",),
        ("rtc_base",), ("pc",), ("p2p",), ("modules",),
        ('video',), ('system_wrappers',), ("net",), ("sdk",),
        ("third_party", "abseil-cpp"), ("third_party", "libjpeg_turbo"),
        ("third_party", "libyuv")
    ]

    for pp in path_list:
        p1 = pp[0]
        p3 = "/".join(pp)
        command = f"rsync -avmq --include='{p3}/**.h' --exclude='test' --exclude='libvpx' --exclude='libaom' -f 'hide,! */' /root/webrtc/src/{p1} package/include"
        logging.debug(command)
        os.system(command)


def collect_library(path):
    logging.info("collecting library")

    library_path = path + "/obj/libwebrtc.a"
    if not os.path.isfile(library_path):
        logging.error(f"library [{library_path}] not exist")
        return

    dest_path = "package/lib"

    if sys.platform == "linux" or sys.platform == "linux2":
        dest_path = dest_path + "/linux"
    elif sys.platform == "darwin":
        dest_path = dest_path + "/mac"
    elif sys.platform == "win32":
        dest_path = dest_path + "/win"

    os.makedirs(dest_path, exist_ok=True)

    logging.info(library_path)
    logging.info(dest_path)

    shutil.copy2(library_path, dest_path)


def main():

    parser = argparse.ArgumentParser(
        description='Collect webrtc header files and libraries.')

    parser.add_argument('-i', '--include', help='include header file path')
    parser.add_argument('-l', '--library', help='library path')
    # parser.add_argument('--enable-audio-volume', dest='eav', action='store_true')
    # parser.add_argument('-s', '--using-scatter', dest='scatter', action='store_true')
    parser.set_defaults(eav=False, scatter=False)

    args = parser.parse_args()

    configure_logging(logging.DEBUG)

    logging.info(args)

    if args.include is not None:
        collect_header(args.include)

    if args.library is not None:
        collect_library(args.library)


if __name__ == "__main__":
    main()
